from python_microservice_sdk.eureka_client import eureka_client

from python_microservice_sdk.http_handler import ExposedError

import pickle
from tornado.escape import json_decode
from python_microservice_sdk import config as cfg


def do_service(app_name: str, service: str, data: dict, method: str = "get", serv_py_only: bool = True):
    result_bytes: bytes = eureka_client.do_service(
        app_name=app_name.upper(),
        service=service,
        return_type='binary',
        method="POST" if serv_py_only else method.upper(),
        data=pickle.dumps(data) if serv_py_only else data,
        headers={"Content-Type":
                 "application/python-pickle" if serv_py_only else "application/json",
                 "MicroClient-Platform":
                 "python"}
    )

    if serv_py_only:
        result: dict = pickle.loads(result_bytes)
    else:
        result: dict = json_decode(result_bytes)
    
    if result.get("code", -1) == 0:
        return result.get("result", None)
    else:
        raise ExposedError(
            code=result.get("code", -1),
            message=result.get("message", "unknown")
        )


if __name__ != "__main__":
    cfg.load_config()
    eureka_client.init(
        **cfg.PYTHON_SERVICE_CONFIG
    )
